package hn.cch.security.configuration;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept
        .FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author CCH
 * @version 2018.09.21
 */
public class SecurityMetadataSource implements
        FilterInvocationSecurityMetadataSource {

    private Map<String, Collection<ConfigAttribute>> configAttributes;

    public SecurityMetadataSource() {
        super();

        Map<String, Collection<ConfigAttribute>> map = new HashMap<>();

        Map<String, String> mapUrlRoles = new HashMap<>();
        mapUrlRoles.put("/**/new", "role|vip");
        mapUrlRoles.put("/**/edit", "role|vip");
        mapUrlRoles.put("/**/delete", "role|vip");
        mapUrlRoles.put("/**/show", "role|vip");
        Set<String> keySet = mapUrlRoles.keySet();
        for (String url : keySet) {
            String[] roles = mapUrlRoles.get(url).split("|");

            Collection<ConfigAttribute> configAttributes = new ArrayList<>();
            for (String role : roles) {
                ConfigAttribute configAttribute = new SecurityConfig(role);
                configAttributes.add(configAttribute);
            }
            map.put(url, configAttributes);
        }
        this.configAttributes = map;
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws
            IllegalArgumentException {

        if (o instanceof FilterInvocation) {
            FilterInvocation filterInvocation = (FilterInvocation) o;
            PathMatcher pathMatcher = new AntPathMatcher();
            Iterator<String> iterator = configAttributes.keySet().iterator();
            while (iterator.hasNext()) {
                if (pathMatcher.match(iterator.next(), filterInvocation
                        .getRequestUrl())) {
                    return configAttributes.get(filterInvocation
                            .getRequestUrl());
                }
            }
            return null;
        }
        return null;

    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
